package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Server2 {
    private ServerSocket serverSocket;

    public Server2() throws IOException {
        serverSocket = new ServerSocket(8088);
        System.out.println("启动服务器成功");
    }

    void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                System.out.println(socket.getInetAddress().getHostAddress()+"连接上了");
                Thread th = new Thread(new ClientHandler(socket));
                th.start();
            }
            // System.out.println(is.read());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        Server2 server = new Server2();
        server.start();
    }

    class ClientHandler implements Runnable {
        private Socket socket;
        private String host;
        ClientHandler(Socket s) {
            this.socket = s;
            this.host=socket.getInetAddress().getHostAddress();
        }

        @Override
        public void run() {
            try {
                InputStream is = null;
                is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String line;
                // System.out.println("客户端说:"+br.readLine());
                // while ((line=br.readLine())!=null)
                while (true) {
                    if ((line=br.readLine()) == null)
                        break;
                    System.out.println(host+"说:"+line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
